package com.heima.behavior.service.impl;

import com.heima.behavior.service.CollectionBehaviorService;
import com.heima.common.util.LoginUserInfo;
import com.heima.common.util.UserInfoThreadLocal;
import com.heima.model.behavior.dto.CollectionBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.enums.BehaviorRedisKeyEnum;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class CollectionBehaviorServiceImpl implements CollectionBehaviorService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 收藏或取消收藏
     * @param dto 收藏行为参数
     * @return ResponseResult
     */
    @Override
    public ResponseResult collect(CollectionBehaviorDto dto) {
        // 1.检查参数
        if (dto.getArticleId() == null || dto.getOperation() == null) {
            return ResponseResult.error(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        // 2.获取当前用户
        LoginUserInfo user = UserInfoThreadLocal.get();
        if (user == null) {
            return ResponseResult.error(AppHttpCodeEnum.NEED_LOGIN);
        }

        // 3.根据操作类型执行收藏或取消收藏
        String collectionKey = BehaviorRedisKeyEnum.COLLECTION_BEHAVIOR_PREFIX.buildKey(dto.getArticleId());

        if (dto.getOperation() == 0) {
            // 收藏操作，添加到Redis set中
            stringRedisTemplate.opsForSet().add(collectionKey, String.valueOf(user.getId()));
        } else {
            // 取消收藏操作，从Redis set中移除
            stringRedisTemplate.opsForSet().remove(collectionKey, String.valueOf(user.getId()));
        }

        return ResponseResult.success(AppHttpCodeEnum.SUCCESS);
    }
}
